import {Button, Checkbox, Form, Input, Card, Typography, Modal} from 'antd';
import React from 'react';
import {PageContainer} from "@ant-design/pro-components";
import {getUserInfo, ShowError} from "@/utils/format";
import {ChangePasswordAPI} from "@/services/DashApi";
import {ServerMessages} from "@/services/ServerMessages";

const App = () => {
  const onFinish = (values) => {
    console.log('Success:', values);
    const {oldpassword, newpassword, newpassword2} = values
    if (newpassword !== newpassword2) {
      ShowError("两次输入的密码不一致！")
      return
    }
    const testPassword = /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[!#@*&.])[a-zA-Z\d!#@*&.]*$/
    if (!testPassword.test(newpassword) || newpassword2.length < 6 || newpassword2.length > 18) {
      ShowError("密码为6-18位，必须包含数字、符号、大小写字母！")
      return
    }
    const {username} = getUserInfo()
    ChangePasswordAPI("/api/alter-pwd-internal", username, oldpassword, newpassword).then(response => {
      Modal.info({
        title: response.message,
        onOk() {
          location.reload()
        },
      });
    }, () => {
      ShowError(ServerMessages.error_message)
    })
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <PageContainer title="修改密码" content={<Typography.Text type="danger">
      1.密码为6-18位，必须包含数字、符号、大小写字母；
      <br/>2.如忘记密码请联系管理员。
    </Typography.Text>}>
      <Card bordered={false}>
        <Form
          name="basic"
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 20,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="旧密码"
            name="oldpassword"
            rules={[
              {
                required: true,
                message: '不能为空!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newpassword"
            rules={[
              {
                required: true,
                message: '不能为空!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            label="确认密码"
            name="newpassword2"
            rules={[
              {
                required: true,
                message: '不能为空!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 4,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default App;
